package com.novabluetooth.services.hqxd;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import com.health.NovaApplication;
import com.health.R;
import com.health.model.ArchiveBaseInfo;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.SBCL_DATA;
import com.nova.BaseActivity;
import com.novabluetooth.bean.ECG;
import com.novabluetooth.data.GlobalContsBlueThooth;
import com.novabluetooth.data.ecgxmlparse.ECGParser;
import com.novabluetooth.data.ecgxmlparse.PullECGParser;
import com.novabluetooth.services.BluetoothConstant;

import android.app.Activity;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

/**
 * 华清心电
 * 
 * @author nova
 *
 */
public class HQXDActivity extends BaseActivity {
	private static final String TAG = "HQXDActivity";

	private final int REQUESTCODE = 0;
	private Button btn_back;
	private Button btn_up;

	private Button btn_Start;

	private TextView tv_title;
	private BluetoothManager mBluetoothManager;
	private String IDCARD = "";
	private ARCHIVE_BASEINFO userInfo = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sbcl_hqxd);
		userInfo = NovaApplication.getUserInfo();
		if (userInfo != null) {
			IDCARD = userInfo.getIDCARD();
			if (TextUtils.isEmpty(IDCARD)) {
				return;
			}
		}
		findViews();
		setListeners();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO 自动生成的方法存根
		super.onActivityResult(requestCode, resultCode, data);
		Log.w("华清心仪-----返回结果", "requestCode=" + requestCode + ";resultCode=" + resultCode + ";data=" + data);
		// requestCode=0;resultCode=0;data=null
		// requestCode=0;resultCode=-1;data=Intent { (has extras) }
		// showTextDialog(
		// "onActivityResult()" + "\n requestCode=" + requestCode +
		// ";resultCode=" + resultCode + ";data=" + data);
		ECG ecg = null;
		if (requestCode == REQUESTCODE && resultCode == Activity.RESULT_OK) {
			if (data.getExtras().getBoolean("AnalysisSuccess")) {
				ecg = getDataFromApp(data);
			} else {
				// 没有结果返回时
				ecg = getDataFromXML();
			}

		} else if (requestCode == REQUESTCODE && resultCode == 0 && data == null) {
			ecg = null;
			showTextDialog("没有测量数据");
		}
		try {
			if (ecg != null) {
				if (ecg.getDataFileName() != null) {
					Log.w(TAG, ecg.toString());
					// 数据文件存在
					showTextDialog("保存成功");
					/// storage/emulated/0/ECGDATA/JPEG/-20160315132210.jpeg

					String str_result = ecg.getDiagnoseResult();
					String heartRate = String.valueOf(ecg.getHeartRate());

					// if (!TextUtils.isEmpty(str_result)) {
					saveData(ecg.getImageName(), str_result, heartRate);
					// }else{
					// saveData(ecg.getImageName(), "无心电图诊断");
					// }

					System.out.println(ecg.getImageName() + "心电图地址");
					// Intent intent = new Intent(getApplicationContext(),
					// ShowPicActivity.class);
					// Intent intent = new Intent(getApplicationContext(),
					// SBCLActivity.class);
					// intent.putExtra("JPG_URL", ecg.getImageName());
					// startActivity(intent);
					Intent intent = new Intent(BluetoothConstant.REGISTER_GB);
					intent.putExtra("JPG_URL", ecg.getImageName());
					mContext.sendBroadcast(intent);

					HQXDActivity.this.finish();
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * 保存结果到数据库
	 * 
	 * @param imgUrl
	 * @param str_result
	 * @author 王婷婷
	 * @date 2016年1月15日 下午12:03:39
	 */
	private void saveData(String imgUrl, String str_result, String heartRate) {
		UUID uuidECG = UUID.randomUUID();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateECG = df.format(new Date());
		Log.e("eeeeeeeeeeeeeeeee2222", "ee_" + str_result);
		if (str_result == null) {
			str_result = "";
		}
		saveCLData("华清心仪", "华清心仪", "心电图片", imgUrl, "心电图片", uuidECG.toString(), IDCARD, dateECG);
		saveCLData("华清心仪", "华清心仪", "心电诊断结果", str_result, "心电诊断结果", uuidECG.toString(), IDCARD, dateECG);
		saveCLData("华清心仪", "华清心仪", "心率", heartRate, "心率", uuidECG.toString(), IDCARD, dateECG);
	}

	/**
	 * 保存测量数据
	 * 
	 * @param device_name
	 * @param device_type
	 * @param cl_type
	 * @param cl_value
	 * @param cl_type_name
	 * @param GUID
	 * @param IDCARD
	 * @param cl_time
	 * @author 王婷婷
	 * @date 2016年1月15日 上午11:52:10
	 */
	public void saveCLData(String device_name, String device_type, String cl_type, String cl_value, String cl_type_name,
			String GUID, String IDCARD, String cl_time) {
		SBCL_DATA sbcl_Data = new SBCL_DATA();
		sbcl_Data.setDEVICE_NAME(device_name);
		sbcl_Data.setDEVICE_TYPE(device_type);
		sbcl_Data.setCL_TYPE(cl_type);
		sbcl_Data.setCL_VALUE(cl_value);
		sbcl_Data.setCL_TYPE_NAME(cl_type_name);
		sbcl_Data.setGUID(GUID);
		sbcl_Data.setIDCARD(IDCARD);
		sbcl_Data.setCL_TIME(cl_time);
		sbcl_Data.setIS_UPDATE("Y");
		NovaApplication.fdbmanger.save(sbcl_Data);
	}

	public void findViews() {
		btn_back = (Button) this.findViewById(R.id.btn_back);
		btn_up = (Button) this.findViewById(R.id.btn_up);
		btn_up.setVisibility(View.GONE);
		btn_Start = (Button) findViewById(R.id.start_cl);
		tv_title = (TextView) findViewById(R.id.title);
		tv_title.setText("华清心仪");
	}

	public void setListeners() {
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				HQXDActivity.this.finish();

			}
		});

		btn_Start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				try {
					ComponentName componentName = new ComponentName("com.ecgmac.ecgtab",
							"com.ecgmac.ecgtab.ECG_Main_Activity");
					Intent intent = new Intent();
					Bundle bundle = new Bundle();

					if (userInfo == null) {
						return;
					}
					bundle.putString("Patient_Name", userInfo.getCUSTOMERNAME());
					bundle.putString("Patient_ID", IDCARD);
					String str_sex = userInfo.getSEX();
					String str_sex_name = "";
					/** 1:男,2:女,0:未知的性别,9:未说明的性别 */
					if (str_sex.equals("1")) {
						str_sex_name = "男";
					} else if (str_sex.equals("2")) {
						str_sex_name = "女";
					} else if (str_sex.equals("0")) {
						str_sex_name = "未知的性别";
					} else if (str_sex.equals("9")) {
						str_sex_name = "未说明的性别";
					}
					bundle.putString("Patient_Gender", str_sex_name);

					java.util.Calendar born = java.util.Calendar.getInstance();
					Date bornTime = userInfo.getBIRTHDAY();
					if (bornTime != null) {
						// born.setTime(bornDate);
						born.setTime(bornTime);
						bundle.putInt("Birth_Year", born.get(Calendar.YEAR));
						bundle.putInt("Birth_Month", born.get(Calendar.MONTH) + 1);
						bundle.putInt("Birth_Day", born.get(Calendar.DAY_OF_MONTH));
						int int_birth = GlobalContsBlueThooth.getAge(bornTime);
						bundle.putInt("Patient_Age", int_birth);
					}

					bundle.putBoolean("StartAD", true); // true = 启动后 自动采集 false
					bundle.putString("Export_Mode", "JPEG"); // 导出模式, PDF, JPEG,
																// XML 三种可选

					// if (mBluetoothManager == null) {
					// mBluetoothManager = (BluetoothManager)
					// getSystemService(Context.BLUETOOTH_SERVICE);
					// }
					// BluetoothAdapter mBluetoothAdapter =
					// mBluetoothManager.getAdapter();
					// if (mBluetoothAdapter == null) {
					// bundle.putString("BTAddress", ""); // 蓝牙地址
					// // 可不传,会自己查找蓝牙采集盒
					// } else {
					// Log.w("eeeeeeeetttttttt", "tt--" +
					// mBluetoothAdapter.getAddress());
					// bundle.putString("BTAddress",
					// mBluetoothAdapter.getAddress()); // 蓝牙地址
					// // 可不传,会自己查找蓝牙采集盒
					// }

					intent.putExtras(bundle);
					intent.setComponent(componentName);
					startActivityForResult(intent, REQUESTCODE);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 获取心电APP返回数据
	 * 
	 * @author 王婷婷
	 * @date 2017年3月20日 下午4:16:10
	 */
	private ECG getDataFromApp(Intent data) {
		ECG ecg = new ECG();

		ecg.setHeartRate(data.getExtras().getInt("HeartRate"));
		ecg.setpWidth(data.getExtras().getInt("PWidth"));
		ecg.setpRInterval(data.getExtras().getInt("PR_Interval"));
		ecg.setqRSDuration(data.getExtras().getInt("QRS_Duration"));
		ecg.setqTC(data.getExtras().getInt("QTc_Interval"));
		ecg.setqTD(data.getExtras().getInt("QT_Interval"));
		ecg.setpAxis(data.getExtras().getInt("P_Axis"));
		ecg.setqRSAxis(data.getExtras().getInt("QRS_Axis"));
		ecg.settAxis(data.getExtras().getInt("T_Axis"));
		ecg.setrV5(data.getExtras().getFloat("RV5"));
		ecg.setsV1(data.getExtras().getFloat("SV1"));
		ecg.setRv5sv1(data.getExtras().getFloat("RV5SV1"));

		ecg.setDataFileName(data.getExtras().getString("DataFileName"));
		ecg.setImageName(data.getExtras().getString("ImageName"));
		ecg.setDiagnoseResult(data.getExtras().getString("DiagnoseResult"));

		return ecg;

	}

	/**
	 * 从xml文件读取
	 * 
	 * @author 王婷婷
	 * @date 2017年3月20日 下午4:24:38
	 */
	private ECG getDataFromXML() {
		ECG ecg = new ECG();
		try {
			String ecg_path = Environment.getExternalStorageDirectory() + BluetoothConstant.ECG_PATH_XML;
			String efgname = GlobalContsBlueThooth.getLastModifiedName(ecg_path);

			if (efgname.equals("")) {
				Log.w(TAG, "没有心电图");
				showTextDialog("请先进行心电采集");
				return null;
			}
			Log.w(TAG, efgname);
			File path = new File(ecg_path, efgname);
			FileInputStream fis = new FileInputStream(path);
			ECGParser ecgparser = new PullECGParser();
			ecg = ecgparser.parse(fis); // 解析输入流
			ecg.setDataFileName(ecg_path + efgname);// 存取xml文件

			// 设置jpeg路径
			String prefix = efgname.substring(0, efgname.lastIndexOf("."));
			String img_filepath = Environment.getExternalStorageDirectory() + BluetoothConstant.ECG_PATH_JPEG + prefix
					+ ".jpeg";
			Log.w(TAG, img_filepath);
			File file_image = new File(img_filepath);
			if (file_image.exists()) {
				ecg.setImageName(img_filepath);
			} else {
				ecg.setImageName("");
			}

			Log.i(TAG, ecg.toString());

		} catch (Exception e) {
			Log.e(TAG, "tt" + e.getMessage());
		}
		return ecg;
	}
}